<template>
  <div class="flex-col-gap" style="padding: 20px;">
    <view>单条字幕时长（单位：秒）</view>
    <el-input-number v-model="num" :step="1"></el-input-number>
    <el-upload @change="file1" class="upload-demo" :auto-upload="false" :show-file-list="false" drag>
      <el-icon class="el-icon--upload"><upload-filled /></el-icon>
      <div class="el-upload__text">
        拖拽或点击选择文本文件（文件中字幕一句一行），生成临时字幕文件
      </div>
    </el-upload>


    <view style="margin-top: 50px;">调整字幕间隔（单位：秒）</view>
    <el-input-number v-model="num2" :precision="1" :step="0.5"></el-input-number>
    <div class="flex-row-gap flex-a-center">
      <view>视频帧数（用于对齐视频帧）</view>
      <el-select v-model="frame" placeholder="视频帧数" style="width: 200px;">
        <el-option
          v-for="item in dictFrame"
          :key="item.value"
          :label="item.label"
          :value="item.value"></el-option>
      </el-select>
    </div>
    <el-upload @change="file2" class="upload-demo" :auto-upload="false" :show-file-list="false" drag>
      <el-icon class="el-icon--upload"><upload-filled /></el-icon>
      <div class="el-upload__text">
        拖拽或点击选择srt文件，调整字幕时间间隙
      </div>
    </el-upload>
  </div>
</template>

<script setup lang="ts">

import { UploadFilled } from '@element-plus/icons-vue'
import { saveAs } from "file-saver";
import { ref } from 'vue';
import moment from 'moment';

const num = ref(10)
const num2 = ref(0)
const frame = ref(30)

const dictFrame = [
  { label: "30帧", value: 30 },
  { label: "60帧", value: 60 },
]

// 将秒数转换为 SRT 格式的时间字符串
function formatTime(seconds: number): string {
  const hours = Math.floor(seconds / 3600);
  const minutes = Math.floor((seconds % 3600) / 60);
  const secs = Math.floor(seconds % 60);
  const millis = Math.round((seconds - Math.floor(seconds)) * 1000);
  return `${String(hours).padStart(2, '0')}:${String(minutes).padStart(2, '0')}:${String(secs).padStart(2, '0')},${String(millis).padStart(3, '0')}`;
}

// 将 SRT 格式的时间字符串转换为秒数
function parseTime(timeStr: string): number {
  const [hms, ms] = timeStr.split(',');
  const [h, m, s] = hms.split(':').map(Number);
  return h * 3600 + m * 60 + s + parseInt(ms, 10) / 1000;
}

// 获取不带扩展名的文件名
function getFileNameWithoutExtension(fileName: string): string {
  // 查找最后一个点的位置
  const lastDotIndex = fileName.lastIndexOf('.');
  // 如果存在点，截取点之前的部分，否则返回原文件名
  return lastDotIndex === -1 ? fileName : fileName.slice(0, lastDotIndex);
}

function file1(e: any) {
  const file = e;
  const fileName = getFileNameWithoutExtension(file.name)

  if (file) {
    const reader = new FileReader();
    // 当文件读取完成时触发
    reader.onload = (event) => {
      let fileContent = event.target?.result as string;
      if (fileContent) {
        fileContent = fileContent.replace(/\r/g, "")
        const lines = fileContent.split('\n');
        let srtContent = '';
        let startTime = 0;
        const duration = num.value; // 每条字幕显示 3 秒
        
        lines.forEach((line, index) => {
          if (!line) {
            return
          }
          const endTime = startTime + duration;
          srtContent += `${index + 1}\n`;
          srtContent += `${formatTime(startTime)} --> ${formatTime(endTime)}\n`;
          srtContent += `${line}\n\n`;
          startTime = endTime;
        });

        const blob = new Blob([srtContent], { type: 'text/plain;charset=utf-8' });
        saveAs(blob, `${fileName} ${moment().format("YYYY-MM-DD HH_mm_ss")}.srt`);
      }
    };
    // 以文本形式读取文件
    reader.readAsText(file.raw);
  }
}

function file2(e: any) {
  const file = e;
  const fileName = getFileNameWithoutExtension(file.name)
  if (file) {
    const reader = new FileReader();
    // 当文件读取完成时触发
    reader.onload = (event) => {
      let fileContent = event.target?.result as string;
      if (fileContent) {
        fileContent = fileContent.replace(/\r/g, "")

        // 分割字幕条目
        const entries = fileContent.split('\n\n').filter(entry => entry.trim());
        let newSrtContent = '';
        let prevEndTime = 0;

        entries.forEach((entry, index) => {
          const lines = entry.split('\n');
          const number = lines[0];
          const [startTimeStr, endTimeStr] = lines[1].split(' --> ');
          const text = lines.slice(2).join('\n');

          // 解析原时间
          const originalStartTime = parseTime(startTimeStr);
          const originalEndTime = parseTime(endTimeStr);
          const originalDuration = originalEndTime - originalStartTime;

          // 计算新的开始时间

          const newStartTime = prevEndTime + (index == 0 ? 0 : num2.value);
          let newEndTime = newStartTime + originalDuration;

          // 如果时间间隔改为0，所有的字幕要对齐视频帧，不然导入后会出现字幕重叠的问题
          const videoFrame = frame.value
          if (num2.value == 0) {
            // 算出最接近的下一帧
            let nextFrame = Math.ceil(newEndTime * videoFrame / 1)
            console.log(nextFrame);

            newEndTime = nextFrame * 1 / videoFrame
            console.log(newEndTime);
          }

          newSrtContent += `${number}\n`;
          newSrtContent += `${formatTime(newStartTime)} --> ${formatTime(newEndTime)}\n`;
          newSrtContent += `${text}\n\n`;

          prevEndTime = newEndTime;
        });

        const blob = new Blob([newSrtContent], { type: 'text/plain;charset=utf-8' });
        saveAs(blob, `${fileName}(已调整间隔) ${moment().format("YYYY-MM-DD HH_mm_ss")}.srt`);
      }
    };
    // 以文本形式读取文件
    reader.readAsText(file.raw);
  }
}
</script>

<style scoped></style>
